package com.example.jsontoexcel.controller;

import com.example.jsontoexcel.model.CashDetail;
import com.example.jsontoexcel.model.ResponseData;
import com.example.jsontoexcel.service.ExcelService;
import com.example.jsontoexcel.service.CounterService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class JsonToExcelController {

    @Autowired
    private ExcelService excelService;
    
    @Autowired
    private CounterService counterService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("usageCount", counterService.getCount());
        return "index";
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.getSize() > 10 * 1024 * 1024) { // 10MB限制
                return ResponseEntity.badRequest().body("文件大小超过限制");
            }

            String content = new String(file.getBytes());
            counterService.incrementCount();
            return processJsonContent(content);

        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件处理失败: " + e.getMessage());
        }
    }

    @PostMapping("/paste")
    @ResponseBody
    public ResponseEntity<?> handleJsonPaste(@RequestBody String jsonContent) {
        try {
            if (jsonContent.getBytes().length > 10 * 1024 * 1024) { // 10MB限制
                return ResponseEntity.badRequest().body("数据大小超过限制");
            }

            counterService.incrementCount();
            return processJsonContent(jsonContent);

        } catch (IOException e) {
            return ResponseEntity.badRequest().body("数据处理失败: " + e.getMessage());
        }
    }

    private String preprocessJson(String content) {
        // 1. 清理多余的空格、换行符和制表符
        content = content.replaceAll("\\s+", " ").trim();
        
        // 2. 处理没有逗号分隔的多个JSON对象
        content = content.replaceAll("}\\s*\\{", "},{");
        
        // 3. 处理属性名没有双引号的情况
        Pattern propertyPattern = Pattern.compile("([{,])\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*:");
        Matcher propertyMatcher = propertyPattern.matcher(content);
        StringBuffer processedContent = new StringBuffer();
        
        while (propertyMatcher.find()) {
            propertyMatcher.appendReplacement(processedContent, 
                propertyMatcher.group(1) + "\"" + propertyMatcher.group(2) + "\":");
        }
        propertyMatcher.appendTail(processedContent);
        
        // 4. 处理单引号值
        content = processedContent.toString();
        Pattern valuePattern = Pattern.compile(":\\s*'([^']*)'");
        Matcher valueMatcher = valuePattern.matcher(content);
        processedContent = new StringBuffer();
        
        while (valueMatcher.find()) {
            valueMatcher.appendReplacement(processedContent, 
                ":\"" + valueMatcher.group(1).replace("\"", "\\\"") + "\"");
        }
        valueMatcher.appendTail(processedContent);
        
        // 5. 如果内容不是以[开头，将其包装在数组中
        content = processedContent.toString();
        if (!content.startsWith("[") && !content.endsWith("]")) {
            content = "[" + content + "]";
        }
        
        return content;
    }

    private ResponseEntity<?> processJsonContent(String content) throws IOException {
        try {
            // 预处理JSON内容
            content = preprocessJson(content);
            
            // 尝试直接解析为ResponseData对象
            ResponseData responseData = objectMapper.readValue(content, ResponseData.class);
            List<CashDetail> cashDetails = responseData.getRows();
            if (cashDetails == null) {
                cashDetails = new ArrayList<>();
            }
            return generateExcelResponse(cashDetails);
        } catch (IOException e) {
            try {
                // 如果直接解析失败，尝试解析为ResponseData数组
                List<ResponseData> responseDataList = objectMapper.readValue(content, 
                    new TypeReference<List<ResponseData>>() {});
                
                List<CashDetail> allCashDetails = new ArrayList<>();
                for (ResponseData responseData : responseDataList) {
                    if (responseData.getRows() != null) {
                        allCashDetails.addAll(responseData.getRows());
                    }
                }
                return generateExcelResponse(allCashDetails);
            } catch (IOException ex) {
                throw new IOException("JSON格式不正确，请确保数据格式为单个ResponseData对象或ResponseData对象数组");
            }
        }
    }

    private ResponseEntity<?> generateExcelResponse(List<CashDetail> cashDetails) throws IOException {
        if (cashDetails.isEmpty()) {
            return ResponseEntity.badRequest().body("没有找到有效的数据");
        }

        byte[] excelBytes = excelService.exportToExcel(cashDetails);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "cash_details.xlsx");

        return ResponseEntity.ok()
                .headers(headers)
                .body(excelBytes);
    }
} 